package com.wen.common.utils;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Data
@PropertySource("classpath:/wx.properties")
public class DownloadImgUtil {

    @Value("${dirPath}")
    private String dirPath;

    public String downloadImg2Local(String sourcesUrl) {
        System.out.println("------------------>" + dirPath);
        InputStream is = null;
        FileOutputStream os = null;
        String fileName = null;
        try {
            URL url = new URL(sourcesUrl);
            URLConnection con = url.openConnection();
            is = con.getInputStream();
            byte[] bs = new byte[1024];
            int len;
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            String formatDate = formatter.format(date);
            String[] split = formatDate.split("-");
            fileName = dirPath + "/" + formatDate + "/" +
                    "pic_" + new Date().getTime() + ".jpg";
            File file = new File(fileName);
            File parentFile = file.getParentFile();
            boolean mkdirs = parentFile.mkdirs();
            //System.out.println(mkdirs);
            if (!file.exists()) {
                boolean newFile = file.createNewFile();
                //System.out.println(newFile);
            }
            os = new FileOutputStream(file, true);
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return fileName;
    }

}
